package com.lanlian.cayman.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lanlian.cayman.LLApplication;
import com.lanlian.cayman.R;
import com.lanlian.cayman.activity.LoginActivity;
import com.lanlian.cayman.fragment.MarketFragment;
import com.lanlian.cayman.proto.ProtoManager;
import com.lanlian.cayman.socket.MySocketManager;
import com.lanlian.cayman.socket.SocketCallImpl;
import com.lanlian.cayman.utils.NumberManager;
import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.PositionDetailsInfo;
import com.lanlian.commonlib.dao.DBManager;
import com.lanlian.commonlib.data.RespIsTrade;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.util.EventBusUtils;
import com.oms.rpc.protobuf.FuturesTradeInfo;
import com.oms.rpc.protobuf.FuturesTradeResp;
import com.oms.rpc.protobuf.OMSTradeReq;
import com.oms.rpc.protobuf.OMSTradeRsp;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.util.ArrayList;

/**
 * 下单对话框
 */
public class PlaceOrderDialogManager implements View.OnClickListener{
    BaseActivity context;
    View view;
    private MagicIndicator mMagicIndicator;
    private ViewPager mViewPager;
    private String[] mTitleList = new String[]{"市价下单", "限价下单"};
    private ArrayList<View> pagerItemList = new ArrayList<>();
   // HqMsg.YsHqInfo yh;
    private  String num;
    RespIsTrade rt;
    BaseResponse baseResponse;
    EditText tv_num;
   private ArrayList<PositionDetailsInfo>  mList;
    /**
     * 合约id
     */
    private String id;
    /**
     * 合约id
     */
    private int chicang_id;
    /**
     * 0 市价单
     */
    private  String price;
    /**
     * 买卖方向X卖出开仓、Y买入平仓、V买入开仓、W卖出平仓
     */
    private String price_type;
    private String order_type;
    /**
     * 交易时间判断类型 1 开仓 2平仓
     */
    private String trade_type="1";
    /**
     * 平仓类型
     */
    private int ping_type=1;
    EditText et_price2;
    String cprice;
    TextView tv_id;
    PositionDetailsInfo p;
    String name;
    Dialog dialog;
    /**
     * 平仓状态 1 当前有多仓 买置灰  2当前有空仓 卖置灰
     * 其他状态不管
     */
    private int pingcang=0;
    /**
     * 最小变动单位
     */
    String scale= "1";
    /**
     * 最小变动单位小数点数
     */
    int scale_count= 2;
    TextView tv_buy;
    TextView tv_sell;
    int cindex=0;
    /**
     * Context context
     */
    public PlaceOrderDialogManager(Activity context)
    {
        this.context=(BaseActivity) context;
        initView();


    }

    /**
     * 设置手数
     * @param num
     */
    public void setNum(String num)
    {
        tv_num.setText(num);
    }

    /**
     * 平仓状态 1 当前有多仓 买置灰  2当前有空仓 卖置灰
     * 其他状态不管
     * @param index
     */
    public void setPingCang(int index)
    {
        ping_type=index;
        trade_type="2";
        if(index==1)
        {
            tv_buy.setBackgroundResource(R.drawable.bg_kline_order3);
            tv_sell.setBackgroundResource(R.drawable.bg_kline_order4);
            tv_buy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
        }
        else if(index==2)
        {
            tv_buy.setBackgroundResource(R.drawable.bg_kline_order2);
            tv_sell.setBackgroundResource(R.drawable.bg_kline_order3);
            tv_sell.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
        }
        else
        {
            tv_buy.setBackgroundResource(R.drawable.bg_kline_order2);
            tv_sell.setBackgroundResource(R.drawable.bg_kline_order4);
        }
    }
    /**
     * 持仓id
     * @param id
     */
    public void setChiCangId(int id)
    {

        this.chicang_id=id;

    }
    private void setChiCang(View view,PositionDetailsInfo p)
    {
        this.p=p;
        TextView tv_chicang=view.findViewById(R.id.tv_chicang);

        if(p.getcPositionFlag()!=null)
        {
            //多仓
            if(p.getcPositionFlag().equals("1"))
            {
                tv_chicang.setText("买 "+p.getlCurrentAmount()+" 手");
            }
            else
            {
                tv_chicang.setText("卖 "+p.getlCurrentAmount()+" 手");
            }
        }

    }
    public void setPrice(String cprice)
    {
        if( this.cprice ==null) {
            this.cprice = cprice;
            if (cindex == 1) {
                et_price2.setText(cprice);
            }
        }
    }
    /**
     * 合约id
     * @param id
     */
    public void setData(String id,String name,String cprice)
    {
       // this.yh=yh;
        this.id=id;
        this.name=name;
        this.cprice=cprice;
       // setOnClick(pagerItemList.get(0));
       // setOnClick(pagerItemList.get(1));
        initView2(cindex);
        getPositionDetails();
       // isTrade();

    }
    private void initView()
    {
        LinearLayout ll=new LinearLayout(context);
        view = context.getLayoutInflater().inflate(R.layout.view_place_order,ll,false);
        mMagicIndicator = view.findViewById(R.id.magic_indicator);
        mViewPager = view.findViewById(R.id.view_pager);
        initView2(cindex);
        initFragments();
        initNavigator();
        //tv_buy.setBackgroundResource(MResUtil.getUpBack());
        //tv_sell.setBackgroundResource(MResUtil.getDownBack());

    }
    private void initFragments() {
        LinearLayout ll=new LinearLayout(context);
        // View view1 = context.getLayoutInflater().inflate(R.layout.view_place_order_item, ll,false);
        // View view2= context.getLayoutInflater().inflate(R.layout.view_place_order_item, ll,false);

        View view1=new View(context);
        View view2=new View(context);


        pagerItemList.add(view1);
          pagerItemList.add(view2);

    }

    /**
     * 0市价 1限价
     * @param index
     */
    private  void initView2(int index)
    {

        tv_buy=view.findViewById(R.id.tv_buy);
        tv_buy.setOnClickListener(this);

        tv_sell=view.findViewById(R.id.tv_sell);
        tv_sell.setOnClickListener(this);
        TextView tv_ping=view.findViewById(R.id.tv_ping);
        tv_ping.setOnClickListener(this);
        TextView tv_money=view.findViewById(R.id.tv_money);

        tv_id=view.findViewById(R.id.tv_id);
        tv_num=view.findViewById(R.id.tv_num);

        et_price2=view.findViewById(R.id.et_price2);

        ImageView mImgReduce = view.findViewById(R.id.img_reduce);
        ImageView mImgPlus = view.findViewById(R.id.img_plus);

        ImageView mImgReduce2 = view.findViewById(R.id.img_reduce2);
        ImageView mImgPlus2 = view.findViewById(R.id.img_plus2);


        tv_num.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    if(tv_num.getText()!=null)
                    {
                        tv_num.setSelection(tv_num.getText().toString().length());
                    }

                } else {
                    // 此处为失去焦点时的处理内容
                }
            }
        });
        et_price2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    if(et_price2.getText()!=null)
                    {
                        et_price2.setSelection(et_price2.getText().toString().length());
                    }

                } else {
                    // 此处为失去焦点时的处理内容
                }
            }
        });

        //
        if(index==0)
        {

            et_price2.setText("市价");
            et_price2.setEnabled(false);
            mImgReduce2.setVisibility(View.INVISIBLE);
            mImgPlus2.setVisibility(View.INVISIBLE);
        }
        else
        {
            et_price2.setEnabled(true);
            if(cprice!=null)
            {
                et_price2.setText(cprice);
            }
            else
            {
                et_price2.setText("0");
            }

            mImgReduce2.setVisibility(View.VISIBLE);
            mImgPlus2.setVisibility(View.VISIBLE);
        }


        if(id!=null)
        {
            scale= MarketFragment.getRespMarket().getGoods(id).minChange;
           scale_count=NumberManager.getNumberDecimalDigits(scale);
        }
        mImgReduce2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s1=et_price2.getText().toString();
                if(NumberManager.isDaYu(s1,"0")>0)
                {
                    et_price2.setText(NumberManager.getSubString(s1,scale,scale_count));
                    et_price2.setSelection(NumberManager.getSubString(s1,scale,scale_count).length());
                }
            }
        });

        mImgPlus2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s1=et_price2.getText().toString();
//                boolean b=checkNum(NumberManager.getAddString(s1, "1", -1));
//                if(b)
//                {


                et_price2.setText(NumberManager.getAddString(s1, scale, scale_count));
                et_price2.setSelection(NumberManager.getSubString(s1,scale,scale_count).length());
   //             }

            }
        });

        mImgReduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s1=tv_num.getText().toString();
                if(NumberManager.isDaYu(s1,"1")>0)
                {
                    tv_num.setText(NumberManager.getSubString(s1,"1",-1));
                    tv_num.setSelection(NumberManager.getSubString(s1,"1",-1).length());
                }
                else
                {
                    Toast.makeText(context,"最低委托1手",Toast.LENGTH_LONG).show();
                }
            }
        });
        mImgPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s1=tv_num.getText().toString();
                if(trade_type.equals("2"))
                {
                    if(NumberManager.isDaYu(s1,p.getlCurrentAmount() - p.getlPresaleAmount()+"")>=0)
                    {
                        return;
                    }
                }
                tv_num.setText(NumberManager.getAddString(s1,"1",-1));
                tv_num.setSelection(NumberManager.getAddString(s1,"1",-1).length());

            }
        });
        if(id!=null)
        {
            tv_id.setText(id);
        }
        tv_money.setText("$"+NumberManager.getString(LLApplication.getAvailableFunds()+"","1",2));
        if(p==null)
        {
            tv_ping.setBackgroundResource(R.drawable.bg_kline_order3);
            tv_ping.setEnabled(false);
        }
        else
        {
            tv_ping.setBackgroundResource(R.drawable.bg_kline_order2);
            tv_ping.setEnabled(true);
        }

        //如果是平仓
        if(trade_type.equals("2"))
        {
            setPingCang(ping_type);
        }
    }

    private void initNavigator() {
        CommonNavigator commonNavigator = new CommonNavigator(context);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mTitleList == null ? 0 : mTitleList.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);

                colorTransitionPagerTitleView.setNormalColor(0xffa1adc8);
                colorTransitionPagerTitleView.setSelectedColor(context.getResources().getColor(R.color.color_text_style4));
                colorTransitionPagerTitleView.setText(mTitleList[index]);
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                       mViewPager.setCurrentItem(index);
                       Log.e("test",index+"");
                       initView2(index);
                       cindex=index;
                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
        mViewPager.setAdapter(new MyAdapter());
        mViewPager.addOnPageChangeListener(new Pageon());
        mViewPager.setCurrentItem(0);
    }
    TradeConfirmDialog tm;
    @Override
    public void onClick(View view) {
        if(!context.mDBManager.isLogined())
        {
            Intent intent=new Intent(context, LoginActivity.class).putExtra("tag", 1);
            context.startActivity(intent);
            return;
        }

        if(checkData()<0)
        {

            return;
        }
//        if(!checkAviadMoney() && !"2".equals(trade_type))
//        {
//            return;
//        }
//        if(!checkNum(num))
//        {
//            return;
//        }
        if(tm!=null&&tm.isShowing())
        {
            return;
        }
        tm=new TradeConfirmDialog(context);
        StringBuffer text=new StringBuffer();
        switch (view.getId())
        {
            case R.id.tv_buy:
                text.append(name);
                text.append("，价格：");
                if(price.equals("0"))
                {
                    text.append("市价");
                }
                else
                {
                    text.append(price);
                }
                text.append("，买：");
                text.append(num+"手");
                order_type="1";
                if(!DBManager.getInstance().getSecondConfirm())
                {

                    tv_buy.setEnabled(false);
                    addData();
                    //isTrade();
                    return;
                }
                if(tm.isShowing())
                {
                    return;
                }
                tm.setText(text.toString());

               tm.setOnOk(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       view.setEnabled(false);
                       addData();
                   }
               });
                tm.showDialog();
            break;
            case R.id.tv_sell:
                text.append(name);
                text.append("，价格：");
                if(price.equals("0"))
                {
                    text.append("市价");
                }
                else
                {
                    text.append(price);
                }
                text.append("，卖：");
                text.append(num+"手");
                order_type="2";
                if(!DBManager.getInstance().getSecondConfirm())
                {
                    tv_sell.setEnabled(false);
                    addData();
                    //isTrade();
                    return;
                }
                if(tm.isShowing())
                {
                    return;
                }
                tm.setText(text.toString());
                tm.setOnOk(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        view.setEnabled(false);

                        addData();
                        //isTrade();
                    }
                });
                tm.showDialog();
                break;
            case R.id.tv_ping:
                if(mList==null||p==null)
                {
                    return;
                }
                text.append(name);
                text.append("，价格：");
                if(price.equals("0"))
                {
                    text.append("市价");
                }
                else
                {
                    text.append(price);
                }

                text.append("，平仓：");
                text.append(num+"手");
                order_type="3";

                if(!DBManager.getInstance().getSecondConfirm())
                {
                    addData();
                    //isTrade();
                    return;
                }
                if(tm.isShowing())
                {
                    return;
                }
                tm.setText(text.toString());
                tm.setOnOk(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        addData();
                        //isTrade();
                    }
                });
                tm.showDialog();
                break;
                default:
                    break;
        }
    }

    public class MyAdapter extends PagerAdapter
    {

        @Override
        public int getCount() {
            return pagerItemList.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView(pagerItemList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            //viewpger 两个页面循环滑动会出现崩溃问题 下面是解决方案

            container.addView(pagerItemList.get(position));
            return pagerItemList.get(position);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return  arg0==arg1;
        }

        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return POSITION_NONE;
        }
    }
    class Pageon implements ViewPager.OnPageChangeListener
    {

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageSelected(int arg0) {

            mViewPager.setCurrentItem(arg0);
            initView2(arg0);

        }

    }

    public boolean showDialog()
     {

         dialog=new Dialog(context,R.style.MyDialog);

         dialog.setContentView(view);


         Window w = dialog.getWindow();
         w.setWindowAnimations(com.lanlian.uikit.R.style.animFromBottom);
         WindowManager.LayoutParams lp = w.getAttributes();
         lp.gravity = Gravity.BOTTOM;
         lp.width= lp.MATCH_PARENT;
         lp.height= lp.WRAP_CONTENT;
         dialog.onWindowAttributesChanged(lp);
         dialog.setCanceledOnTouchOutside(true);
         dialog.getWindow().setAttributes(lp);
         dialog.getWindow().getDecorView().setPadding(0, 0, 0, 0);
         dialog.show();
         return  true;

     }
     public boolean isShow()
     {
         if(dialog!=null&&dialog.isShowing())
         {
             return true;
         }
         return  false;
     }
    public void showDialog2()
    {
        dialog=new Dialog(context,R.style.MyDialog);

        dialog.setContentView(view);


        Window w = dialog.getWindow();
        w.setWindowAnimations(com.lanlian.uikit.R.style.animFromBottom);
        WindowManager.LayoutParams lp = w.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width= lp.WRAP_CONTENT;
        lp.height= lp.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(lp);
        dialog.setCanceledOnTouchOutside(true);
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().getDecorView().setPadding(0, 0, 0, 0);
        dialog.show();

    }
     private void getData()
     {
         int item=mViewPager.getCurrentItem();
         //View view=mViewPager.getChildAt(item);
         //TextView tv_price=view.findViewById(R.id.tv_price2);
         EditText et_price=view.findViewById(R.id.et_price2);
         TextView tv_num=view.findViewById(R.id.tv_num);
         num=tv_num.getText().toString();
         if(item==0)
         {

             price="0";
             price_type="1";
         }
         else
         {
             price= et_price.getText().toString();
             price_type="2";
         }


     }
     private int checkData()
     {
         getData();
         if(num==null||"".equals(num)||"0".equals(num))
         {
             Toast.makeText(context,"请输入数量",Toast.LENGTH_LONG).show();
             return -1;
         }
         if (trade_type.equals("2")) {

             if(p!=null&&NumberManager.isDaYu(num,p.getlCurrentAmount() - p.getlPresaleAmount()+"") > 0)
             {
                 Toast.makeText(context,"数量超出限制",Toast.LENGTH_LONG).show();
                 return -1;
             }
         }
         if(!TextUtils.isEmpty(price))
         {
             if("0".equals(price)) {
                 if(mViewPager.getCurrentItem()==1) {
                     Toast.makeText(context, "价格不能为零", Toast.LENGTH_LONG).show();
                     return -1;
                 }
             }
         } else {
             Toast.makeText(context, "请输入价格0", Toast.LENGTH_LONG).show();
             return -1;
         }
         return 0;
     }

     public void addData()
     {
         try {
             context.showLoadingDialog();
//             if(rt==null&&baseResponse==null)
//             {
//                 return;
//             }
//            if(baseResponse==null)
//             {
//                 return;
//             }
//             if(baseResponse!=null)
//             {
//                 context.showToast(baseResponse.getMsg());
//                 return;
//             }
//             if(!rt.getCode().equals("0")||!rt.getFlag())
//             {
//                context.showToast(rt.getMsg());
//                return;
//             }


//             OMSTradeReq.Builder oms=new ProtoManager().getRequst(3);
//             OMSTradeReq om=oms.build();
             ProtoManager pm=new ProtoManager();


             FuturesTradeInfo.Builder fb=pm.getFuturesTradeInfoBuilder();
             //fb.setCExchangeNo(yh.getExchangeID());
             fb.setVcFuturesCode(id);
             fb.setLOrderAmount(Long.parseLong(num));
             fb.setEnOrderPrice(Double.parseDouble(price));
             fb.setCPriceType(price_type);
             fb.setCOrderDirection(order_type);
             fb.setLPositionNo(chicang_id);
             if ("2".equals(trade_type)) {
                 fb.setLOrderType(8);
             }
            //下面的方法必须最后调用
             OMSTradeReq.Builder oms=pm.getRequst(1);
             OMSTradeReq om=oms.build();

             SocketCallImpl sc=new SocketCallImpl(context){
                 @Override
                 public void message(byte[] data) {
                     tv_sell.setEnabled(true);
                     tv_buy.setEnabled(true);
                     try {
                         OMSTradeRsp oms=  OMSTradeRsp.parseFrom(data);
                         if (oms.getRequestStatus() == 0) {
                             FuturesTradeResp fr=oms.getFuturestradeResp();
                             tm.dismiss();
                             if (fr.getErrcode() == 0) {
                                 Toast.makeText(context,"委托请求成功",Toast.LENGTH_SHORT).show();
                                 EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                                 EventBusUtils.post(new EventMessage(EventCode.EVENT_ENTRUST_REFRESH));
                                 EventBusUtils.post(new EventMessage(EventCode.EVENT_POSITION_REFRESH));
                                 dialog.dismiss();
                             } else {
                                 Toast.makeText(context,fr.getErrmsg(),Toast.LENGTH_SHORT).show();
                             }
                         }
                         else if(oms.getRequestStatus()==2) {
                             Toast.makeText(context, "登录过期", Toast.LENGTH_SHORT).show();
                             DBManager.getInstance().setLoginOut();
                             EventBusUtils.post(new EventMessage(EventCode.EVENT_LOGIN_OUT_REFRESH));
                             EventBusUtils.post(new EventMessage(EventCode.EVENT_FUCK_OUT_REFRESH));
                         } else {
                             tm.dismiss();
                             Toast.makeText(context,oms.getStatusInfo(),Toast.LENGTH_SHORT).show();
                         }
                     } catch (Exception e) {
                         tm.dismiss();
                         e.printStackTrace();
                         Toast.makeText(context,"服务连接异常",Toast.LENGTH_SHORT).show();
                     }
                 }
             };
             MySocketManager ms=new MySocketManager();
             ms.sendData(om.toByteArray(),sc);
         }catch (Exception e)
         {
             e.printStackTrace();
             Toast.makeText(context,e.getMessage(),Toast.LENGTH_LONG).show();

         }



     }

    /**
     * 获取持仓信息
     */
    private void getPositionDetails() {
        mList = LLApplication.getPositionList();
        if (id !=null && mList != null) {
            PositionDetailsInfo p;
            for (int i=0; i<mList.size(); i++){
                p=mList.get(i);
                if(p.getVcContractCode().equals(id)) {
                    setChiCang(view,p);
                    chicang_id = Integer.parseInt(p.getlPositionNo()+"");
                }
            }
        }
    }

}
